<script setup lang="ts">
import { onMounted, onBeforeUnmount } from 'vue';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { mapOptions, attribution } from '@/constants/map';

// leaflet 地图实例
let map: L.Map | null = null;
// GeoJSON数据
const PolygonJson: any = [
	{
		type: 'Feature',
		properties: { party: 'Republican', name: '三角形' },
		geometry: {
			type: 'Polygon',
			coordinates: [
				[
					[116.36266649031123, 39.9265471461217],
					[116.38806443675763, 39.901251181144445],
					[116.32971780302944, 39.903623074730504],
				],
			],
		},
	},
	{
		type: 'Feature',
		properties: { party: 'Democrat', name: '矩形' },
		geometry: {
			type: 'Polygon',
			coordinates: [
				[
					[116.42101312403938, 39.898088528642596],
					[116.42101312403938, 39.92443950588346],
					[116.46940650848451, 39.92443950588346],
					[116.46940650848451, 39.898088528642596],
				],
			],
		},
	},
];

// 创建地图
const createMap = () => {
	// 创建地图实例
	map = L.map('leafletMap', mapOptions);
	// 加载图层
	L.tileLayer(import.meta.env.VITE_GAODE_MAP, {
		// 如果设置此项为true，则切片不会用重复填充来表示世界范围（经度-180到180之间）之外的地方
		noWrap: true,
		// 左下角版权信息
		attribution,
	}).addTo(map);
	// 添加GeoJSON数据 在地图中显示
	L.geoJSON(PolygonJson, {
		style: feature => {
			// 设置数据的颜色
			const colorObj = {
				Republican: { color: '#ff0000' },
				Democrat: { color: '#0000ff' },
			};
			return (colorObj as any)[feature?.properties.party];
		},
	})
		.on('mouseover', e => {
			// 设置鼠标悬浮事件
			if (!map) return;
			// 解析选中数据的类型名
			const type = e.propagatedFrom.feature.properties.name;
			// 在鼠标悬浮位置添加Popup标注
			L.popup().setContent(type).setLatLng(e.latlng).openOn(map);
		})
		.addTo(map);
};

// 初始化地图
const initMap = () => {
	createMap();
};
// 创建地图
onMounted(() => {
	initMap();
});
// 销毁地图
onBeforeUnmount(() => {
	map?.remove();
	map = null;
});
</script>

<template>
	<div class="map-view">
		<div id="leafletMap" class="map"></div>
	</div>
</template>

<style lang="less" scoped>
@import url('./index.less');
</style>
